package com.vivebest.utils.kd.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *     pod版本配置
 * </p>
 *
 * @author zsk
 * @date 2020/8/15 下午5:16
 */
@Configuration
@Log4j2
public class PodVersionConfig {

    @Value("${k8s.pod-version.init-file}")
    private String podVersionInitFile;

    public static String podVersionHashName="podVersion";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 自定义初始化方法
     */
    @PostConstruct
    public void init() {
        initPodVersion();
    }

    private void initPodVersion() {
        try(BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(new File(podVersionInitFile))))){
            Map<String, String> podVersion = new HashMap<String, String>();
            bufferedReader.lines().forEach(oneLine->{
                String[] oneLineBySplit=oneLine.split(":");
                podVersion.put(oneLineBySplit[0], oneLineBySplit[1]);
            });
            // 存入一个散列数据类型
            stringRedisTemplate.opsForHash().putAll(podVersionHashName, podVersion);
            log.debug("pod版本初始化完成");
        }catch (FileNotFoundException e) {
            log.warn("pod版本初始化文件不存在:{}",podVersionInitFile);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
